package com.windoent.yugioh.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.Gravity;
import android.widget.TextView;

import com.windoent.yugioh.R;
import com.windoent.yugioh.help.zyyoonacity.AddressPickTask;
import com.windoent.yugioh.inteface.CitySelectInterface;
import com.windoent.yugioh.widget.dialog.SucessFailAutoDismissDialog;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.DateTimePicker;
import cn.qqtheme.framework.picker.NumberPicker;
import cn.qqtheme.framework.picker.OptionPicker;
import cn.qqtheme.framework.widget.WheelView;

/**
 * author : robert
 * date   : 2021/4/26 14:29
 * desc   :
 */
public class BaseMethod {
    //判断存在且不为null
    public static boolean notNull(String string) {
        return string != null && !TextUtils.isEmpty(string) && !string.equals("null");
    }

    public static boolean isNull(String string) {
        return string == null || TextUtils.isEmpty(string) || string.equals("null");
    }

    //判断存在且不为null,返回默认值
    public static String notNullDefaultValue(String string, String defaultStr) {
        return notNull(string) ? string : notNull(defaultStr) ? defaultStr : "";
    }

    //判断存在且不为null,返回默认值
    public static String notNullDefaultValueNull(String string) {
        return notNull(string) ? string : "";
    }

    //Android获取bitmap图片的大小
    public static long getBitmapsize(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            return bitmap.getByteCount();
        }
        return bitmap.getRowBytes() * bitmap.getHeight();

    }

    //日期选择
    @SuppressLint("SimpleDateFormat")
    public static void showSelectDate(final Calendar calendar, final Context context, final TextView textView, final boolean flag) {
        DatePickerDialog dialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(android.widget.DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                calendar.set(year, monthOfYear, dayOfMonth);
                if (flag && calendar.getTime().getTime() > new Date().getTime()) {
                    ToastUtils.showText(context.getString(R.string.string_select_correct_date));
                    return;
                }
                String birthday = DateFormat.format("yyy-MM-dd", calendar).toString();
                textView.setText(birthday);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        try {
            dialog.getDatePicker().setMinDate(new SimpleDateFormat("yyyy-MM-dd").parse("1950-01-01").getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dialog.show();
    }

    //年月日
    public static void showYearMonthDayPicker(final Activity context, final TextView textView, int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        //年
        int yearCurrent = calendar.get(Calendar.YEAR);
        //月
        int monthCurrent = calendar.get(Calendar.MONTH) + 1;
        //日
        int dayCurrent = calendar.get(Calendar.DAY_OF_MONTH);
        final DatePicker picker = new DatePicker(context);
        picker.setCanceledOnTouchOutside(true);
        picker.setUseWeight(true);
        picker.setRangeEnd(yearCurrent, monthCurrent, dayCurrent);
        picker.setRangeStart(1940, 1, 1);
        picker.setSelectedItem(BaseMethod.notNull(year + "") && year != 0 ? year : yearCurrent, BaseMethod.notNull(month + "") && month != 0 ? month : monthCurrent, BaseMethod.notNull(day + "") && day != 0 ? day : dayCurrent);
        picker.setResetWhileWheel(false);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                textView.setText(year + "-" + month + "-" + day);
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    //省市区选择
    public static void cityPicker(Activity context, TextView textView, String proviceName, String cityName, String countryName, String zoneId, String city_id, String county_id, CitySelectInterface listener) {
        AddressPickTask task = new AddressPickTask(context);
        task.setHideProvince(false);
        task.setHideCounty(false);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressPicked(Province province, City city, County county) {
                if (county == null) {
                    textView.setText(province.getAreaName() + city.getAreaName());
                    if (listener != null) {
                        listener.getId(province.getId(), city.getId(), "");
                    }
                } else {
                    textView.setText(province.getAreaName() + city.getAreaName() + county.getAreaName());
                    if (listener != null) {
                        listener.getId(province.getId(), city.getId(), county.getId());
                    }
                    LogUtils.d("cityPicker---->" + "province.getId():" + province.getId() + "," + city.getId() + "," + county.getId());
                }
            }

            @Override
            public void onAddressInitFailed() {
                ToastUtils.showText(context.getString(R.string.string_init_city_json_fail));
            }

        });
        task.execute(BaseMethod.notNullDefaultValue(proviceName, "上海市"), BaseMethod.notNullDefaultValue(cityName, "上海市"), BaseMethod.notNullDefaultValue(countryName, "普陀区"), BaseMethod.notNullDefaultValue(zoneId, "9"), BaseMethod.notNullDefaultValue(city_id, "774"), BaseMethod.notNullDefaultValue(county_id, "779"));
    }

    /**
     * 将byte转换为更加友好的单位
     *
     * @param sizeInB byte
     * @return 更加友好的单位（KB、GB等）
     */
    public static String readableStorageSize(long sizeInB) {
        float floatSize = sizeInB;
        int index = 0;
        String[] units = new String[]{"B", "KB", "MB", "GB", "TB", "PB"};

        while (floatSize > 1000 && index < 5) {
            index++;
            floatSize /= 1024;
        }

        String capacityText = new DecimalFormat("###,###,###.##").format(floatSize);
        return String.format(Locale.ENGLISH, "%s%s", capacityText, units[index]);
    }

    //随机返回True或False
    public static boolean getRandomBoolean() {
        Random random = new Random();
        return random.nextBoolean();
    }

    //年月日时间选择
    public static void onYearMonthDayTimePicker(Activity context, TextView textView) {
        DateTimePicker picker = new DateTimePicker(context, DateTimePicker.HOUR_24);
        picker.setDateRangeStart(2021, 1, 1);
        picker.setDateRangeEnd(2075, 11, 11);
        picker.setTimeRangeStart(0, 0);
        picker.setTimeRangeEnd(24, 60);
        picker.setTopLineColor(0x99FF0000);
        picker.setLabelTextColor(0xFF0489CE);
        picker.setDividerColor(0xFFDDA0DD);
        picker.setOnDateTimePickListener(new DateTimePicker.OnYearMonthDayTimePickListener() {
            @Override
            public void onDateTimePicked(String year, String month, String day, String hour, String minute) {
                textView.setText(year + "-" + month + "-" + day + " " + hour + ":" + minute);
            }
        });
        picker.show();
    }

    //年月日时间选择
    public static void onYearMonthDayTimePicker(Activity context, DatePicker.OnYearMonthDayPickListener listener) {
        Time time = new Time("GMT+8");
        time.setToNow();
        int year = time.year;
        int month = time.month + 1;
        int day = time.monthDay;
        DatePicker picker = new DatePicker(context, DatePicker.YEAR_MONTH_DAY);
        picker.setGravity(Gravity.BOTTOM);
        picker.setRangeStart(year, month + 1, day);
        picker.setRangeEnd(2100, 1, 1);
        picker.setLabel("年", "月", "日");
        picker.setTopLineColor(0x99FF0000);
        picker.setLabelTextColor(0xFF0489CE);
        picker.setDividerColor(0xFFDDA0DD);
        picker.setOnDatePickListener(listener);
        picker.show();
    }

    //年月日时间选择
    public static void onYearMonthDayTimePicker(Activity context, DateTimePicker.OnYearMonthDayTimePickListener listener) {
        Calendar calendar = Calendar.getInstance();
        //年
        int year = calendar.get(Calendar.YEAR);
        //月
        int month = calendar.get(Calendar.MONTH) + 1;
        //日
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //获取系统时间
        //小时
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //分钟
        int minute = calendar.get(Calendar.MINUTE);
        //秒
        int second = calendar.get(Calendar.SECOND);
        DateTimePicker picker = new DateTimePicker(context, DateTimePicker.HOUR_24);
        picker.setDateRangeStart(year, month, day);
        picker.setDateRangeEnd(2100, 1, 1);
        picker.setTimeRangeStart(hour, minute);
        picker.setTimeRangeEnd(23, 59);
        picker.setTopLineColor(0x99FF0000);
        picker.setLabelTextColor(0xFF0489CE);
        picker.setDividerColor(0xFFDDA0DD);
        picker.setOnDateTimePickListener(listener);
        picker.show();
    }

    //数字选择
    public static void onNumberPicker(Activity context, int number, TextView textView) {
        NumberPicker picker = new NumberPicker(context);
        picker.setCanceledOnTouchOutside(true);
        picker.setWidth(picker.getScreenWidthPixels());
        picker.setCycleDisable(true);
        picker.setDividerVisible(false);
        picker.setOffset(3);//偏移量
        picker.setRange(1, number, 1);//数字范围
        picker.setDividerRatio(WheelView.DividerConfig.FILL);
        picker.setSelectedItem(6);
        picker.setLabel("");
        picker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                textView.setText(item.intValue() + "");
            }
        });
        picker.show();
    }

    //娱乐赛4,8,16，32,64
    public static void selectLunsStrong(Activity context, TextView textView) {
        OptionPicker picker = new OptionPicker(context, new String[]{
                "4", "8", "16", "32", "64"
        });
        picker.setCanceledOnTouchOutside(true);
        picker.setDividerRatio(WheelView.DividerConfig.FILL);
        picker.setSelectedIndex(1);
        picker.setCycleDisable(true);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                textView.setText(item + "");
            }
        });
        picker.show();
    }

    //积分赛选4强 4,8,16
    public static void onOptionStrongPicker(Activity context, TextView textView) {
        OptionPicker picker = new OptionPicker(context, new String[]{
                "4", "8", "16"
        });
        picker.setCanceledOnTouchOutside(true);
        picker.setDividerRatio(WheelView.DividerConfig.FILL);
        picker.setSelectedIndex(1);
        picker.setCycleDisable(true);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                textView.setText(item + "");
            }
        });
        picker.show();
    }

    //https://yugioh-1258002530.cos.ap-shanghai.myqcloud.com/Android/yingdie_crop_20210506125054.png
    public static String getUrlImageSubString(String url) {
        if (notNull(url) && url.contains("Android/")) {
            int index = url.indexOf("Android/");
            String substring = url.substring(index);
            return substring;
        } else
            return url;
    }

    //成功失败提示
    public static void showSucessDialog(Context mContext, String msg, SucessFailAutoDismissDialog.OnInterface listener) {
        SucessFailAutoDismissDialog dialog = new SucessFailAutoDismissDialog(mContext, listener);
        dialog.setTvContent(true, R.drawable.drawable_dialog_sucess, msg, "", "");
        dialog.show();
    }

    //失败提示
    public static void showFailDialog(Context mContext, String msg, String msgFailReason) {
        SucessFailAutoDismissDialog dialog = new SucessFailAutoDismissDialog(mContext, null);
        dialog.setTvContent(false, R.drawable.drawable_dialog_fail, msg, "", msgFailReason);
        dialog.show();
    }

    //提取字符串当中的数字
    public static String getStringNum(String s) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(s);
        return m.replaceAll("").trim();
    }

}
